<template>
  <!-- 企业管理 -->
  <div class="mod-sys__params">
    <el-form :inline="true" :model="tableForm" @keyup.enter="getDataList()">
      <el-form-item prop="id" label="企业名称">
        <el-input v-model.trim="tableForm.name" placeholder="企业名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getDataList()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="clearTableForm()">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateHandle()">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" @click="deleteHandle(selectIdList)">删除</el-button>
      </el-form-item>
    </el-form>

    <el-table ref="tableRef" v-loading="dataListLoading" :data="dataList" border @selection-change="dataListSelectionChangeHandle" style="width: 100%">
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="name" label="企业名称" header-align="center" align="center"></el-table-column>
      <el-table-column prop="maxNum" label="人数限制" header-align="center" align="center"></el-table-column>
      <el-table-column prop="vipStartTime" label="会员起效时间" header-align="center" align="center">
        <template v-slot="scope">
          <span v-if="scope.row.vipStartTime">{{scope.row.vipStartTime?scope.row.vipStartTime.replace('T',' '):''}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="vipEndTime" label="会员过期时间" header-align="center" align="center">
        <template v-slot="scope">
          <span v-if="scope.row.vipEndTime">{{scope.row.vipEndTime?scope.row.vipEndTime.replace('T',' '):''}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="code" label="会员码" header-align="center" align="center"></el-table-column>
      <el-table-column label="操作" fixed="right" header-align="center" align="center" width="150">
        <template v-slot="scope">
          <el-button type="primary" link @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
          <el-button type="primary" link @click="deleteHandle([scope.row.id])">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination :current-page="pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="pageSizeChangeHandle" @current-change="pageCurrentChangeHandle"> </el-pagination>

    <!-- 弹窗, 新增 / 修改 -->
    <el-dialog v-model="visible" :title="!fromDataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :close-on-press-escape="false" width="600px">
      <el-form :model="fromDataForm" :rules="rules" ref="fromDataFormRef" @keyup.enter="fromDataFormSubmitHandle()" label-width="120px">
        <el-form-item prop="name" label="企业名称">
          <el-input v-model.trim="fromDataForm.name" placeholder="企业名称"></el-input>
        </el-form-item>
        <el-form-item prop="code" label="企业编码">
          <el-input v-model.trim="fromDataForm.code" disabled placeholder="企业编码"></el-input>
        </el-form-item>
        <el-form-item prop="maxNum" label="人数限制">
          <el-input-number v-model="fromDataForm.maxNum" class="mx-4" :min="1" controls-position="right" />
        </el-form-item>
        <el-form-item prop="vipStartTime" label="会员起效时间">
          <el-date-picker v-model="fromDataForm.vipStartTime" type="datetime" value-format="YYYY-MM-DDTHH:mm:ss" placeholder="会员起效时间" style="width:100%;" />
        </el-form-item>
        <el-form-item prop="vipEndTime" label="会员结束时间">
          <el-date-picker v-model="fromDataForm.vipEndTime" type="datetime" value-format="YYYY-MM-DDTHH:mm:ss" placeholder="会员结束时间" style="width:100%;" />
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="fromDataFormSubmitHandle()">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, toRefs, onMounted } from "vue";
import baseService from "@/service/baseService";
import { IObject } from "@/types/interface";
import { ElMessage, ElMessageBox } from "element-plus";

// 表格查询
const tableForm = ref({
  name: ""
});

const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 表格加载
const dataListLoading = ref(false);
const tableRef = ref();
//  表格数据
const dataList = ref<IObject[]>([]);
const selectIdList = ref([]);

// 所属企业列表
const enterprisesList = ref([]);

const visible = ref(false);
const fromDataFormRef = ref();

// 表单数据
const fromDataForm = reactive<IObject>({
  id: "",
  name: "",
  code: "",
  maxNum: "",
  vipStartTime: "",
  vipEndTime: ""
});

const rules = ref({
  name: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  maxNum: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  vipStartTime: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  vipEndTime: [{ required: true, message: "必填项不能为空", trigger: "blur" }]
});

// 查询表格数据
const getDataList = (bol: boolean = true) => {
  if (bol) {
    pageNum.value = 1;
    pageSize.value = 10;
  }
  baseService
    .post(`/admin/enterprises/page`, {
      data: {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        ...tableForm.value
      }
    })
    .then((res) => {
      dataList.value = res.data.list;
      total.value = res.data.total;

      if (tableRef.value) {
        tableRef.value.clearSelection();
        selectIdList.value = [];
      }
    });
};

// 重置
const clearTableForm = () => {
  tableForm.value.name = "";
  getDataList();
};

// 新增/修改
const addOrUpdateHandle = async (id: any) => {
  visible.value = true;
  fromDataForm.id = "";

  // 重置表单数据
  if (fromDataFormRef.value) {
    fromDataFormRef.value.resetFields();
  }

  if (id) {
    await getInfo(id);
  }
};

// 删除
const deleteHandle = (ids: []) => {
  if (ids && ids.length <= 0) {
    return ElMessage.error("请选择操作项");
  }

  ElMessageBox.confirm("确定进行删除操作?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      baseService
        .post(`/admin/enterprises/del`, {
          data: {
            ids: ids
          }
        })
        .then((res) => {
          ElMessage.success({
            message: "成功",
            duration: 500
          });
          getDataList();
        });
    })
    .catch(() => {});
};

// 选择表格数据
const dataListSelectionChangeHandle = (val: any) => {
  let ids = val.map((item: any) => item.id);
  selectIdList.value = ids;
};

// 切换分页数
const pageSizeChangeHandle = (val: any) => {
  pageSize.value = val;
  getDataList(false);
};

// 切换页数
const pageCurrentChangeHandle = (val: any) => {
  pageNum.value = val;
  getDataList(false);
};

// 获取信息
const getInfo = async (id: number) => {
  await baseService
    .post(`/admin/enterprises/detail`, {
      data: {
        id: id
      }
    })
    .then((res) => {
      Object.assign(fromDataForm, res.data);
    });
};

// 处理手机号只能输入正整数
const handleInput = (val: any) => {
  // 使用正则表达式过滤非数字字符
  let inputValue;
  inputValue = val.replace(/\D/g, "");
  fromDataForm.mobile = inputValue;
};

// 表单提交
const fromDataFormSubmitHandle = () => {
  fromDataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }

    let url = fromDataForm.id ? "/admin/enterprises/update" : "/admin/enterprises/add";
    baseService
      .post(url, {
        data: fromDataForm
      })
      .then((res: any) => {
        ElMessage.success({
          message: "成功",
          duration: 500,
          onClose: () => {
            visible.value = false;
            getDataList();
          }
        });
      });
  });
};

onMounted(() => {
  getDataList();
  getEnterprisesList();
});

// 获取所属企业列表
const getEnterprisesList = () => {
  baseService.post(`/admin/enterprises/list`).then((res) => {
    enterprisesList.value = res.data;
  });
};

// 处理表格中企业名称
const handlerCode = (code: any) => {
  if (code) {
    let list = enterprisesList.value.filter((item: IObject) => item.code == code) as IObject[];
    return list.length > 0 ? list[0].name : "";
  }
};
</script>
